package com.blank.white.common.util.context;


import com.blank.white.common.util.BaseUtil;
import com.blank.white.common.util.UUIDUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class ContextUtil {




    /**
     * 获取traceId
     *
     * @param
     * @return string
     * @throw
     * @date
     */
    public static String getTraceId() {
        //从本地线程中取对象
        LocalContext context = LocalHolder.get();
        //存在则直接取值
        if (context != null) {
            String traceId = context.getTraceId();
            if (StringUtils.isBlank(traceId)) {
                String newTraceId = getRandomTraceId();
                context.setTraceId(newTraceId);
                return newTraceId;
            }
            return traceId;
        } else { //不存在，在第一次取时新建对象并存入
            context = new LocalContext();
            String newTraceId = getRandomTraceId();
            context.setTraceId(newTraceId);
            LocalHolder.add(context);
            return newTraceId;
        }
    }

    public static String getAppId() {
        LocalContext context = LocalHolder.get();
        String appId = "";
        if (context != null) {
            appId = context.getAppId();
        }
        return appId;
    }

    /**
     * 设置traceId
     *
     * @param traceId
     * @return
     * @throw
     * @date
     */
    public static void setTraceId(String traceId) {
        if (BaseUtil.isNullOrEmpty(traceId)) {
            traceId = getTraceId();
        }
        LocalContext context = LocalHolder.get();
        if (Objects.isNull(context)) {
            context = new LocalContext();
            context.setTraceId(traceId);
            LocalHolder.add(context);
        } else if (StringUtils.isBlank(context.getTraceId())) {
            context.setTraceId(traceId);
        }
    }

    public static void releaseThreadLocals() {
        LocalHolder.remove();
    }

    /**
     * 生成16位随机字符串
     *
     * @return
     */
    public static String getRandomTraceId() {
        return UUIDUtil.getUUID();
    }

    public static Map<String, String> copyContext() {
        return Optional.ofNullable(MDC.getCopyOfContextMap()).orElse(Maps.newHashMap());
    }

    public static LocalContext copyLocalContent() {
        return Optional.ofNullable(LocalHolder.get()).orElse(new LocalContext());
    }


}
